<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>火星云盘系统</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    
    <!-- 自定义样式 -->
    <style>
        :root {
            --primary-color: #2979ff;
            --primary-hover: #1e6fff;
            --primary-light: #e3f2fd;
            --sidebar-width: 220px;
            --header-height: 60px;
            --toolbar-height: 56px;
            --text-primary: #333333;
            --text-secondary: #666666;
            --border-color: #e8e8e8;
            --bg-gray: #f7f8fa;
            --mars-red: #ff6b35;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            background: #f0f2f5;
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* 顶部导航栏 */
        .top-navbar {
            background: linear-gradient(135deg, #2979ff 0%, #1e6fff 100%);
            height: var(--header-height);
            padding: 0 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .logo-section {
            display: flex;
            align-items: center;
            color: white;
            font-size: 20px;
            font-weight: 600;
        }

        .logo-icon {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, var(--mars-red) 0%, #ff8a5b 100%);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-size: 20px;
        }

        .user-section {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .storage-info {
            color: white;
            font-size: 13px;
            background: rgba(255, 255, 255, 0.15);
            padding: 6px 14px;
            border-radius: 20px;
        }

        .user-avatar {
            width: 36px;
            height: 36px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary-color);
            font-size: 18px;
            cursor: pointer;
        }

        /* 主容器 */
        .main-wrapper {
            display: flex;
            margin-top: var(--header-height);
            min-height: calc(100vh - var(--header-height));
        }

        /* 左侧边栏 */
        .sidebar {
            width: var(--sidebar-width);
            background: white;
            border-right: 1px solid var(--border-color);
            padding: 20px 0;
            position: fixed;
            left: 0;
            top: var(--header-height);
            bottom: 0;
            overflow-y: auto;
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-item {
            padding: 12px 24px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            color: var(--text-primary);
            font-size: 14px;
            border-left: 3px solid transparent;
        }

        .sidebar-item i {
            margin-right: 12px;
            font-size: 18px;
            width: 20px;
        }

        .sidebar-item:hover {
            background: var(--bg-gray);
        }

        .sidebar-item.active {
            background: var(--primary-light);
            color: var(--primary-color);
            border-left-color: var(--primary-color);
        }

        /* 主内容区 */
        .main-content {
            margin-left: var(--sidebar-width);
            flex: 1;
            background: white;
            min-height: calc(100vh - var(--header-height));
        }

        /* 面包屑导航 */
        .breadcrumb-bar {
            padding: 16px 24px;
            background: white;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
        }

        .breadcrumb {
            margin: 0;
            padding: 0;
            background: transparent;
            font-size: 14px;
        }

        .breadcrumb-item {
            color: var(--text-secondary);
        }

        .breadcrumb-item a {
            color: var(--text-secondary);
            text-decoration: none;
            transition: color 0.2s;
        }

        .breadcrumb-item a:hover {
            color: var(--primary-color);
        }

        .breadcrumb-item.active {
            color: var(--text-primary);
        }

        .breadcrumb-item + .breadcrumb-item::before {
            content: "/";
            color: #ccc;
        }

        /* 工具栏 */
        .toolbar {
            padding: 16px 24px;
            background: white;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .toolbar-left {
            display: flex;
            gap: 12px;
        }

        .toolbar-right {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        .btn-toolbar {
            padding: 8px 16px;
            border-radius: 4px;
            border: 1px solid var(--border-color);
            background: white;
            color: var(--text-primary);
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .btn-toolbar:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .btn-toolbar.btn-primary-toolbar {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .btn-toolbar.btn-primary-toolbar:hover {
            background: var(--primary-hover);
        }

        .view-switcher {
            display: flex;
            gap: 4px;
        }

        .view-btn {
            width: 32px;
            height: 32px;
            border: 1px solid var(--border-color);
            background: white;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-secondary);
            transition: all 0.2s;
        }

        .view-btn:hover, .view-btn.active {
            border-color: var(--primary-color);
            color: var(--primary-color);
            background: var(--primary-light);
        }

        /* 文件列表 */
        .file-list-container {
            padding: 0;
        }

        .file-list-header {
            display: flex;
            padding: 12px 24px;
            background: var(--bg-gray);
            border-bottom: 1px solid var(--border-color);
            font-size: 13px;
            color: var(--text-secondary);
            font-weight: 500;
        }

        .file-list-header > div {
            padding: 0 8px;
        }

        .col-name {
            flex: 1;
            min-width: 300px;
        }

        .col-size {
            width: 120px;
        }

        .col-date {
            width: 180px;
        }

        .col-actions {
            width: 140px;
            text-align: right;
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 12px 24px;
            border-bottom: 1px solid #f5f5f5;
            transition: all 0.2s;
            cursor: pointer;
        }

        .file-item:hover {
            background: #fafafa;
        }

        .file-item > div {
            padding: 0 8px;
        }

        .file-icon-name {
            flex: 1;
            min-width: 300px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .file-icon {
            font-size: 24px;
            width: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .file-icon.folder {
            color: #ffa726;
        }

        .file-icon.file {
            color: #78909c;
        }

        .file-name {
            color: var(--text-primary);
            font-size: 14px;
            cursor: pointer;
            transition: color 0.2s;
        }

        .file-item[data-is-folder="true"] .file-name:hover {
            color: var(--primary-color);
        }

        .file-size {
            width: 120px;
            color: var(--text-secondary);
            font-size: 13px;
        }

        .file-date {
            width: 180px;
            color: var(--text-secondary);
            font-size: 13px;
        }

        .file-actions {
            width: 140px;
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            opacity: 0;
            transition: opacity 0.2s;
        }

        .file-item:hover .file-actions {
            opacity: 1;
        }

        .action-btn {
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.2s;
            font-size: 14px;
        }

        .action-btn:hover {
            background: var(--primary-light);
            color: var(--primary-color);
        }

        .action-btn.delete:hover {
            background: #ffebee;
            color: #f44336;
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: var(--text-secondary);
        }

        .empty-state i {
            font-size: 80px;
            color: #ddd;
            margin-bottom: 20px;
        }

        .empty-state h4 {
            font-size: 16px;
            color: var(--text-primary);
            margin-bottom: 8px;
        }

        .empty-state p {
            font-size: 14px;
            color: var(--text-secondary);
        }

        /* 模态框 */
        .modal-content {
            border-radius: 8px;
            border: none;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .modal-header {
            background: white;
            border-bottom: 1px solid var(--border-color);
            padding: 16px 24px;
        }

        .modal-title {
            font-size: 16px;
            color: var(--text-primary);
            font-weight: 600;
        }

        .modal-body {
            padding: 24px;
        }

        .modal-footer {
            border-top: 1px solid var(--border-color);
            padding: 16px 24px;
        }

        .form-label {
            font-size: 14px;
            color: var(--text-primary);
            margin-bottom: 8px;
        }

        .form-control {
            border-radius: 4px;
            border: 1px solid var(--border-color);
            padding: 8px 12px;
            font-size: 14px;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(41, 121, 255, 0.1);
        }

        /* 上传区域 */
        .upload-zone {
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
        }

        .upload-zone:hover {
            border-color: var(--primary-color);
            background: var(--primary-light);
        }

        .upload-zone.dragover {
            border-color: var(--primary-color);
            background: var(--primary-light);
        }

        .upload-zone i {
            font-size: 48px;
            color: var(--primary-color);
            margin-bottom: 16px;
        }

        .upload-zone p {
            margin: 8px 0;
            color: var(--text-secondary);
            font-size: 14px;
        }

        .upload-zone p.main-text {
            color: var(--text-primary);
            font-size: 15px;
        }

        /* 加载动画 */
        .loading-spinner {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.3);
            z-index: 9999;
            align-items: center;
            justify-content: center;
        }

        .spinner-border {
            width: 48px;
            height: 48px;
            border-width: 4px;
        }

        /* 按钮样式 */
        .btn {
            border-radius: 4px;
            font-size: 14px;
            padding: 8px 20px;
        }

        .btn-primary {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background: var(--primary-hover);
            border-color: var(--primary-hover);
        }

        /* 文件列表项选中效果 */
        .file-item.selected {
            background: var(--primary-light);
        }

        /* 响应式 */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .main-content {
                margin-left: 0;
            }

            .file-size, .file-date {
                display: none;
            }

            .col-size, .col-date {
                display: none;
            }
        }
    </style>
</head>
<body>

<!-- 顶部导航栏 -->
<div class="top-navbar">
    <div class="logo-section">
        <div class="logo-icon">
            <i class="bi bi-rocket-takeoff-fill"></i>
        </div>
        <span>火星云盘系统</span>
    </div>
    <div class="user-section">
        <div class="storage-info" id="storageInfo" onclick="refreshStorage()" title="点击刷新存储空间" style="cursor: pointer;">
            <i class="bi bi-hdd-fill me-1"></i>
            <span>存储空间：加载中...</span>
        </div>
        <div class="user-avatar" onclick="showUserMenu()" title="退出登录">
            <i class="bi bi-person-fill"></i>
        </div>
    </div>
</div>

<!-- 主容器 -->
<div class="main-wrapper">
    <!-- 左侧边栏 -->
    <div class="sidebar">
        <ul class="sidebar-menu">
            <li class="sidebar-item" th:classappend="${currentType == 'all' || currentType == null ? 'active' : ''}" onclick="navigateToMenu('all')">
                <i class="bi bi-folder-fill"></i>
                <span>全部文件</span>
            </li>
            <li class="sidebar-item" th:classappend="${currentType == 'image' ? 'active' : ''}" onclick="navigateToMenu('image')">
                <i class="bi bi-image-fill"></i>
                <span>图片</span>
            </li>
            <li class="sidebar-item" th:classappend="${currentType == 'document' ? 'active' : ''}" onclick="navigateToMenu('document')">
                <i class="bi bi-file-earmark-text-fill"></i>
                <span>文档</span>
            </li>
            <li class="sidebar-item" th:classappend="${currentType == 'video' ? 'active' : ''}" onclick="navigateToMenu('video')">
                <i class="bi bi-play-circle-fill"></i>
                <span>视频</span>
            </li>
            <li class="sidebar-item" th:classappend="${currentType == 'audio' ? 'active' : ''}" onclick="navigateToMenu('audio')">
                <i class="bi bi-music-note-beamed"></i>
                <span>音频</span>
            </li>
            <li class="sidebar-item" th:classappend="${currentType == 'recent' ? 'active' : ''}" onclick="navigateToMenu('recent')">
                <i class="bi bi-clock-history"></i>
                <span>最近使用</span>
            </li>
            <li class="sidebar-item" onclick="window.location.href='/recycle'">
                <i class="bi bi-trash3-fill"></i>
                <span>回收站</span>
            </li>
        </ul>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-bar">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item">
                        <a href="/"><i class="bi bi-house-door-fill"></i> 全部文件</a>
                    </li>
                    <th:block th:if="${pathParts != null and pathParts.length > 0}">
                        <th:block th:each="part, iterStat : ${pathParts}">
                            <th:block th:if="${!#strings.isEmpty(part)}">
                                <li class="breadcrumb-item" th:classappend="${iterStat.last} ? 'active' : ''">
                                    <th:block th:if="${!iterStat.last}">
                                        <a th:href="@{/(path=${#strings.arrayJoin(#arrays.copyOfRange(pathParts, 0, iterStat.index + 1), '/')})}" 
                                           th:text="${part}"></a>
                                    </th:block>
                                    <th:block th:if="${iterStat.last}" th:text="${part}"></th:block>
                                </li>
                            </th:block>
                        </th:block>
                    </th:block>
                </ol>
            </nav>
        </div>

        <!-- 工具栏 -->
        <div class="toolbar">
            <div class="toolbar-left">
                <button class="btn-toolbar btn-primary-toolbar" data-bs-toggle="modal" data-bs-target="#uploadModal">
                    <i class="bi bi-cloud-upload-fill"></i>
                    <span>上传</span>
                </button>
                <button class="btn-toolbar" data-bs-toggle="modal" data-bs-target="#createFolderModal">
                    <i class="bi bi-folder-plus"></i>
                    <span>新建文件夹</span>
                </button>
                <button class="btn-toolbar" onclick="location.reload()">
                    <i class="bi bi-arrow-clockwise"></i>
                    <span>刷新</span>
                </button>
            </div>
            <div class="toolbar-right">
                <div class="view-switcher">
                    <button class="view-btn active" title="列表视图">
                        <i class="bi bi-list-ul"></i>
                    </button>
                    <button class="view-btn" title="网格视图">
                        <i class="bi bi-grid-3x3-gap"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 文件列表 -->
        <div class="file-list-container">
            <th:block th:if="${files.size() == 0}">
                <div class="empty-state">
                    <i class="bi bi-inbox"></i>
                    <h4>当前文件夹为空</h4>
                    <p>可以上传文件或创建新文件夹</p>
                </div>
            </th:block>

            <th:block th:if="${files.size() > 0}">
                <!-- 列表表头 -->
                <div class="file-list-header">
                    <div class="col-name">文件名</div>
                    <div class="col-size">大小</div>
                    <div class="col-date">修改时间</div>
                    <div class="col-actions">操作</div>
                </div>

                <!-- 文件列表项 -->
                <th:block th:each="file : ${files}">
                    <div class="file-item" 
                         th:attr="data-key=${file.key}, data-name=${file.name}, data-type=${file.type}, data-is-folder=${file.type == 'folder'}">
                        <div class="file-icon-name">
                            <i class="file-icon" th:classappend="${file.type == 'folder' ? 'folder' : 'file'} + ' bi ' + ${file.icon}"></i>
                            <span class="file-name" th:text="${file.name}"></span>
                        </div>
                        <div class="file-size" th:text="${file.formattedSize}"></div>
                        <div class="file-date" th:if="${file.lastModified != null}" 
                             th:text="${#temporals.format(file.lastModified, 'yyyy-MM-dd HH:mm')}"></div>
                        <div class="file-date" th:if="${file.lastModified == null}">-</div>
                        <div class="file-actions">
                            <button class="action-btn preview-btn" th:if="${file.type == 'file'}" 
                                    title="预览">
                                <i class="bi bi-eye"></i>
                            </button>
                            <button class="action-btn download-btn" th:if="${file.type == 'file'}" 
                                    title="下载">
                                <i class="bi bi-download"></i>
                            </button>
                            <button class="action-btn rename-btn" 
                                    title="重命名">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="action-btn delete delete-btn" 
                                    title="删除">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                </th:block>
            </th:block>
        </div>
    </div>
</div>

<!-- 上传文件模态框 -->
<div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-cloud-upload-fill me-2"></i>上传文件
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="upload-zone" id="uploadZone">
                    <i class="bi bi-cloud-arrow-up-fill"></i>
                    <p class="main-text mt-3 mb-1">点击选择文件或拖拽文件到此处</p>
                    <p class="mb-0">支持批量上传，单个文件最大 100MB</p>
                </div>
                <input type="file" id="fileInput" class="d-none" multiple>
                <div id="fileList" class="mt-3"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="uploadFiles()">开始上传</button>
            </div>
        </div>
    </div>
</div>

<!-- 创建文件夹模态框 -->
<div class="modal fade" id="createFolderModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-folder-plus me-2"></i>新建文件夹
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="folderName" class="form-label">文件夹名称</label>
                    <input type="text" class="form-control" id="folderName" placeholder="请输入文件夹名称" autocomplete="off">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="createFolder()">创建</button>
            </div>
        </div>
    </div>
</div>

<!-- 重命名模态框 -->
<div class="modal fade" id="renameModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-pencil-square me-2"></i>重命名
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="newName" class="form-label">新名称</label>
                    <input type="text" class="form-control" id="newName" placeholder="请输入新名称" autocomplete="off">
                    <input type="hidden" id="renameKey">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="renameFile()">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 文件预览模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-eye me-2"></i><span id="previewFileName">文件预览</span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="previewContent" style="min-height: 400px; max-height: 70vh; overflow: auto;">
                <!-- 预览内容将在这里动态加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="downloadFromPreview">
                    <i class="bi bi-download me-1"></i>下载
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 加载动画 -->
<div class="loading-spinner" id="loadingSpinner">
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
    </div>
</div>

<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- 自定义脚本 -->
<script th:inline="javascript">
    const currentPath = /*[[${currentPath}]]*/ '';

    // 事件委托处理文件操作
    document.addEventListener('DOMContentLoaded', function() {
        const fileListContainer = document.querySelector('.file-list-container');
        
        if (fileListContainer) {
            // 使用事件委托处理所有文件项的点击
            fileListContainer.addEventListener('click', function(e) {
                const fileItem = e.target.closest('.file-item');
                if (!fileItem) return;
                
                const key = fileItem.dataset.key;
                const name = fileItem.dataset.name;
                const isFolder = fileItem.dataset.isFolder === 'true';
                
                // 点击文件名导航到文件夹
                if (e.target.closest('.file-name') && isFolder) {
                    navigateToFolder(key);
                    return;
                }
                
                // 点击预览按钮
                if (e.target.closest('.preview-btn')) {
                    previewFile(key, name);
                    return;
                }
                
                // 点击下载按钮
                if (e.target.closest('.download-btn')) {
                    downloadFile(key);
                    return;
                }
                
                // 点击重命名按钮
                if (e.target.closest('.rename-btn')) {
                    showRenameModal(key, name);
                    return;
                }
                
                // 点击删除按钮
                if (e.target.closest('.delete-btn')) {
                    const fileSize = fileItem.querySelector('.file-size') ? 
                        parseSizeToBytes(fileItem.querySelector('.file-size').textContent) : 0;
                    deleteFile(key, isFolder, fileSize);
                    return;
                }
            });
        }
        
        // 加载用户信息和存储空间
        loadUserInfo();
    });
    
    // 菜单导航
    function navigateToMenu(type) {
        if (type === 'all') {
            window.location.href = '/';
        } else {
            window.location.href = '/?type=' + type;
        }
    }
    
    // 显示用户菜单
    function showUserMenu() {
        if (confirm('确定要退出登录吗？')) {
            window.location.href = '/user/logout';
        }
    }
    
    // 加载用户信息
    async function loadUserInfo() {
        try {
            const response = await fetch('/user/info');
            const result = await response.json();
            
            if (result.success && result.data) {
                updateStorageDisplay(result.data);
            }
        } catch (error) {
            console.error('加载用户信息失败', error);
        }
    }
    
    // 刷新存储空间统计
    async function refreshStorage() {
        const storageInfoEl = document.getElementById('storageInfo');
        const originalHTML = storageInfoEl.innerHTML;
        
        // 显示刷新中状态
        storageInfoEl.innerHTML = `
            <i class="bi bi-arrow-clockwise me-1"></i>
            <span>刷新中...</span>
        `;
        
        try {
            const response = await fetch('/user/refresh-storage', {
                method: 'POST'
            });
            const result = await response.json();
            
            if (result.success && result.data) {
                updateStorageDisplay(result.data);
                showAlert('存储空间已刷新', 'success');
            } else {
                storageInfoEl.innerHTML = originalHTML;
                showAlert('刷新失败', 'warning');
            }
        } catch (error) {
            storageInfoEl.innerHTML = originalHTML;
            console.error('刷新存储空间失败', error);
        }
    }
    
    // 更新存储空间显示
    function updateStorageDisplay(userInfo) {
        const storageInfoEl = document.getElementById('storageInfo');
        if (storageInfoEl) {
            storageInfoEl.innerHTML = `
                <i class="bi bi-hdd-fill me-1"></i>
                <span title="${userInfo.storageUsedFormatted} / ${userInfo.storageLimitFormatted}">
                    存储空间：${userInfo.storageUsagePercent}% (${userInfo.storageUsedFormatted})
                </span>
            `;
        }
    }

    // 文件上传
    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('fileInput');
    const fileList = document.getElementById('fileList');
    let selectedFiles = [];

    uploadZone.addEventListener('click', () => fileInput.click());

    uploadZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadZone.classList.add('dragover');
    });

    uploadZone.addEventListener('dragleave', () => {
        uploadZone.classList.remove('dragover');
    });

    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
        handleFiles(e.dataTransfer.files);
    });

    fileInput.addEventListener('change', (e) => {
        handleFiles(e.target.files);
    });

    function handleFiles(files) {
        selectedFiles = Array.from(files);
        displayFileList();
    }

    function displayFileList() {
        fileList.innerHTML = '';
        selectedFiles.forEach((file, index) => {
            const fileItem = document.createElement('div');
            fileItem.className = 'alert alert-info d-flex justify-content-between align-items-center';
            fileItem.innerHTML = `
                <span><i class="bi bi-file-earmark me-2"></i>${file.name} (${formatFileSize(file.size)})</span>
                <button class="btn btn-sm btn-danger" onclick="removeFile(${index})">
                    <i class="bi bi-x"></i>
                </button>
            `;
            fileList.appendChild(fileItem);
        });
    }

    function removeFile(index) {
        selectedFiles.splice(index, 1);
        displayFileList();
    }

    async function uploadFiles() {
        if (selectedFiles.length === 0) {
            showAlert('请选择要上传的文件', 'warning');
            return;
        }

        showLoading();
        const uploadPromises = selectedFiles.map(file => uploadSingleFile(file));
        
        try {
            await Promise.all(uploadPromises);
            hideLoading();
            showAlert('文件上传成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('uploadModal')).hide();
            
            // 刷新存储空间信息
            await loadUserInfo();
            
            setTimeout(() => location.reload(), 1000);
        } catch (error) {
            hideLoading();
            showAlert('文件上传失败: ' + error.message, 'danger');
        }
    }

    async function uploadSingleFile(file) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('path', currentPath);

        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();
        if (!result.success) {
            throw new Error(result.message);
        }
    }

    // 创建文件夹
    async function createFolder() {
        const folderName = document.getElementById('folderName').value.trim();
        if (!folderName) {
            showAlert('请输入文件夹名称', 'warning');
            return;
        }

        showLoading();
        const formData = new FormData();
        formData.append('folderName', folderName);
        formData.append('path', currentPath);

        try {
            const response = await fetch('/folder', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            hideLoading();

            if (result.success) {
                showAlert(result.message, 'success');
                bootstrap.Modal.getInstance(document.getElementById('createFolderModal')).hide();
                
                // 刷新存储空间信息
                await loadUserInfo();
                
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(result.message, 'danger');
            }
        } catch (error) {
            hideLoading();
            showAlert('创建文件夹失败', 'danger');
        }
    }

    // 导航到文件夹
    function navigateToFolder(key) {
        window.location.href = '/?path=' + encodeURIComponent(key);
    }

    // 预览文件
    let currentPreviewKey = '';
    
    function previewFile(key, fileName) {
        currentPreviewKey = key;
        const ext = getFileExtension(fileName).toLowerCase();
        const previewContent = document.getElementById('previewContent');
        const previewFileName = document.getElementById('previewFileName');
        const previewUrl = '/preview?key=' + encodeURIComponent(key);
        
        previewFileName.textContent = fileName;
        
        // 根据文件类型显示不同的预览内容
        if (isImageFile(ext)) {
            // 图片预览
            previewContent.innerHTML = `
                <div class="text-center">
                    <img src="${previewUrl}" class="img-fluid" style="max-width: 100%; max-height: 60vh;" alt="${fileName}">
                </div>
            `;
        } else if (isVideoFile(ext)) {
            // 视频预览
            previewContent.innerHTML = `
                <div class="text-center">
                    <video controls style="max-width: 100%; max-height: 60vh;">
                        <source src="${previewUrl}" type="video/${ext}">
                        您的浏览器不支持视频播放。
                    </video>
                </div>
            `;
        } else if (isAudioFile(ext)) {
            // 音频预览
            const audioType = getAudioMimeType(ext);
            previewContent.innerHTML = `
                <div class="text-center p-5">
                    <i class="bi bi-music-note-beamed" style="font-size: 80px; color: #6b7280;"></i>
                    <h5 class="mt-3">${fileName}</h5>
                    <audio controls class="w-100 mt-4">
                        <source src="${previewUrl}" type="${audioType}">
                        您的浏览器不支持音频播放。
                    </audio>
                </div>
            `;
        } else if (ext === 'pdf') {
            // PDF预览
            previewContent.innerHTML = `
                <iframe src="${previewUrl}" style="width: 100%; height: 60vh; border: none;"></iframe>
            `;
        } else if (isTextFile(ext)) {
            // 文本文件预览
            fetch(previewUrl)
                .then(response => response.text())
                .then(text => {
                    previewContent.innerHTML = `
                        <pre style="background: #f5f5f5; padding: 20px; border-radius: 8px; max-height: 60vh; overflow: auto;"><code>${escapeHtml(text)}</code></pre>
                    `;
                })
                .catch(error => {
                    previewContent.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-triangle me-2"></i>文件预览失败
                        </div>
                    `;
                });
        } else {
            // 不支持预览的文件类型
            previewContent.innerHTML = `
                <div class="text-center p-5">
                    <i class="bi bi-file-earmark" style="font-size: 80px; color: #6b7280;"></i>
                    <h5 class="mt-3">暂不支持此文件类型的预览</h5>
                    <p class="text-muted">文件类型：.${ext}</p>
                    <button class="btn btn-primary mt-3" onclick="downloadFile('${key}')">
                        <i class="bi bi-download me-2"></i>下载文件
                    </button>
                </div>
            `;
        }
        
        // 显示预览模态框
        new bootstrap.Modal(document.getElementById('previewModal')).show();
    }
    
    // 从预览模态框下载文件
    document.getElementById('downloadFromPreview').addEventListener('click', function() {
        if (currentPreviewKey) {
            downloadFile(currentPreviewKey);
        }
    });
    
    // 判断是否为图片文件
    function isImageFile(ext) {
        return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(ext);
    }
    
    // 判断是否为视频文件
    function isVideoFile(ext) {
        return ['mp4', 'webm', 'ogv', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(ext);
    }
    
    // 判断是否为音频文件
    function isAudioFile(ext) {
        return ['mp3', 'wav', 'ogg', 'oga', 'm4a', 'flac', 'aac', 'wma', 'opus'].includes(ext);
    }
    
    // 获取音频MIME类型
    function getAudioMimeType(ext) {
        const mimeTypes = {
            'mp3': 'audio/mpeg',
            'wav': 'audio/wav',
            'ogg': 'audio/ogg',
            'oga': 'audio/ogg',
            'm4a': 'audio/mp4',
            'flac': 'audio/flac',
            'aac': 'audio/aac',
            'wma': 'audio/x-ms-wma',
            'opus': 'audio/opus'
        };
        return mimeTypes[ext] || 'audio/' + ext;
    }
    
    // 判断是否为文本文件
    function isTextFile(ext) {
        return ['txt', 'md', 'json', 'xml', 'html', 'css', 'js', 'java', 'py', 'c', 'cpp', 'log', 'csv'].includes(ext);
    }
    
    // 获取文件扩展名
    function getFileExtension(fileName) {
        if (!fileName || fileName.indexOf('.') === -1) {
            return '';
        }
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }
    
    // HTML转义
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // 下载文件
    function downloadFile(key) {
        window.location.href = '/download?key=' + encodeURIComponent(key);
    }

    // 显示重命名模态框
    function showRenameModal(key, currentName) {
        document.getElementById('renameKey').value = key;
        document.getElementById('newName').value = currentName;
        new bootstrap.Modal(document.getElementById('renameModal')).show();
    }

    // 重命名
    async function renameFile() {
        const key = document.getElementById('renameKey').value;
        const newName = document.getElementById('newName').value.trim();

        if (!newName) {
            showAlert('请输入新名称', 'warning');
            return;
        }

        showLoading();
        try {
            const response = await fetch(`/rename?key=${encodeURIComponent(key)}&newName=${encodeURIComponent(newName)}`, {
                method: 'PUT'
            });
            const result = await response.json();
            hideLoading();

            if (result.success) {
                showAlert(result.message, 'success');
                bootstrap.Modal.getInstance(document.getElementById('renameModal')).hide();
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(result.message, 'danger');
            }
        } catch (error) {
            hideLoading();
            showAlert('重命名失败', 'danger');
        }
    }

    // 删除文件
    async function deleteFile(key, isFolder, fileSize) {
        if (!confirm(isFolder ? '确定要删除此文件夹吗？' : '确定要将此文件移至回收站吗？')) {
            return;
        }

        showLoading();
        try {
            const url = `/delete?key=${encodeURIComponent(key)}&isFolder=${isFolder}&fileSize=${fileSize || 0}`;
            const response = await fetch(url, {
                method: 'DELETE'
            });
            const result = await response.json();
            hideLoading();

            if (result.success) {
                showAlert(result.message, 'success');
                
                // 刷新存储空间信息
                await loadUserInfo();
                
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(result.message, 'danger');
            }
        } catch (error) {
            hideLoading();
            showAlert('删除失败', 'danger');
        }
    }
    
    // 将文件大小转换为字节数
    function parseSizeToBytes(sizeStr) {
        if (!sizeStr || sizeStr === '-') return 0;
        const match = sizeStr.match(/^([\d,.]+)\s*([A-Z]+)$/);
        if (!match) return 0;
        
        const value = parseFloat(match[1].replace(/,/g, ''));
        const unit = match[2];
        
        const units = {'B': 1, 'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024};
        return Math.floor(value * (units[unit] || 1));
    }

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    }

    // 显示加载动画
    function showLoading() {
        document.getElementById('loadingSpinner').style.display = 'flex';
    }

    // 隐藏加载动画
    function hideLoading() {
        document.getElementById('loadingSpinner').style.display = 'none';
    }

    // 显示提示消息
    function showAlert(message, type) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 80px; right: 24px; z-index: 10000; min-width: 320px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); border-radius: 8px; border: none;';
        
        let icon = '';
        if (type === 'success') icon = '<i class="bi bi-check-circle-fill me-2"></i>';
        else if (type === 'danger') icon = '<i class="bi bi-exclamation-circle-fill me-2"></i>';
        else if (type === 'warning') icon = '<i class="bi bi-exclamation-triangle-fill me-2"></i>';
        else if (type === 'info') icon = '<i class="bi bi-info-circle-fill me-2"></i>';
        
        alertDiv.innerHTML = `
            ${icon}${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(alertDiv);

        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }
</script>

</body>
</html>

